package com.alex.service;

import cn.hutool.core.convert.Convert;
import co.elastic.clients.elasticsearch._types.FieldValue;
import co.elastic.clients.elasticsearch._types.query_dsl.*;
import co.elastic.clients.json.JsonData;
import com.alex.paramVo.ArticleSearchVo;
import com.alex.service.Search_Plans.*;
import com.alex.utils.CheckUtil;
import com.alex.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.time.Year;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.alex.utils.MyUtils.zsout;


/**
 * @author xiaoyuer
 * @daet 2020/4/2 7:01 下午
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class FilterService {

    @Autowired
    private HttpSession session;
    @Autowired
    private FirstAnalysisService firstAnalysisService;


    public BoolQuery.Builder getBoolQuery(ArticleSearchVo searchVo) throws SQLException, IOException {
        BoolQuery.Builder allQueryBuilder = new BoolQuery.Builder();

        //特殊情况一 用户检索词中含有&符号,将其替换成#z#a#f#n#fd#
        String searchWord = searchVo.getPram();
        if (searchWord.startsWith("id=")) {//aid
            searchWord = searchWord.replace("id=", "");
            if (CheckUtil.isNumberRange(searchWord)) {
                String[] split = searchWord.split(",");
                List<FieldValue> values = new ArrayList<>();
                for (String id : split) {
                    values.add(FieldValue.of(id));
                }
                Query idsQuery = TermsQuery.of(t -> t.field("aid").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
                allQueryBuilder.must(idsQuery);
            }

        } else if (searchWord.startsWith("pmid=")) {
            searchWord = searchWord.replace("pmid=", "");
            if (CheckUtil.isNumberRange(searchWord)) {
                String[] split = searchWord.split(",");
                List<FieldValue> values = new ArrayList<>();
                for (String id : split) {
                    values.add(FieldValue.of(id));
                }
                Query idsQuery = TermsQuery.of(t -> t.field("pmid").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
                allQueryBuilder.must(idsQuery);
            }
        } else if (CheckUtil.isNumber(searchWord)) {
            //判断是不是pmid
            searchWord = searchWord.replaceAll("\\[pmid\\]", "");
            searchWord = searchWord.replaceAll("\\[PMID\\]", "");
            String finalPram1 = searchWord;
            TermQuery query = TermQuery.of(i -> i.field("pmid").value(k -> k.stringValue(finalPram1)));
            allQueryBuilder.must(query._toQuery());
            return allQueryBuilder;
        } else {
            /**
             * 核心检索
             */
            allQueryBuilder.must(firstAnalysisService.getQuery(searchWord, true));
        }

        /**
         * 如果是课题思路助手 和高分选题 只要pm数据
         */
        if (searchVo.getType() != null) {
            if (searchVo.getType().equalsIgnoreCase("QF_Study_Topic_Idea_Assistant") || searchVo.getType().equalsIgnoreCase("HIGH_SCORING_TOPICS")) {
                allQueryBuilder.mustNot(TermQuery.of(i -> i.field("pmid").value(0))._toQuery());
            }
        }

        /**
         * 如果是高分选题,只要摘要不为空的
         */
        if (searchVo.getType() != null) {
            if (searchVo.getType().equalsIgnoreCase("HIGH_SCORING_TOPICS")) {
                allQueryBuilder.mustNot(MatchQuery.of(i -> i.field("ab").query("null"))._toQuery());
            }
        }

        /**
         * 影响因子过滤
         */
        if (StringUtil.isNotNull(searchVo.getJif())) {
            String[] strings = searchVo.getJif().split("###");
            BoolQuery.Builder builder = new BoolQuery.Builder();
            for (String string : strings) {
                String[] split = string.split("_");
                System.out.println("多选影响因子左侧_" + split[0]);
                System.out.println("多选影响因子右侧_" + split[1]);
                System.out.println("--------------");
                Query rangeQuery = RangeQuery.of(i -> i.field("jcr_if").gte(JsonData.fromJson(split[0] + ".0")).lte(JsonData.fromJson(split[1] + ".0")))._toQuery();
                builder.should(rangeQuery);
            }
            allQueryBuilder.must(builder.build()._toQuery());
        }
        /**
         * 年份过滤
         */
        if (CheckUtil.isNotNull(searchVo.getYears())) {
            String pubyear = searchVo.getYears();
            if (pubyear.contains("_")) {
                String[] split = pubyear.split("_");
                Query rangeQuery = RangeQuery.of(i -> i.field("year").gte(JsonData.fromJson(split[0] + ".0")).lte(JsonData.fromJson(split[1] + ".0")))._toQuery();
                allQueryBuilder.must(rangeQuery);
            } else {
                Query toQuery = TermQuery.of(i -> i.field("year").value(pubyear))._toQuery();
                allQueryBuilder.must(toQuery);
            }

        }

        /**
         * 中科院分区
         */
        if (null != searchVo.getZkyDaLei()) {
            List<String> list = covent(searchVo.getZkyDaLei());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("zkydalei").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * JCR分区
         */
        if (null != searchVo.getJcrFenQu()) {
            List<String> list = covent(searchVo.getJcrFenQu());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("jcr_quartile").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        /**
         * 近三年
         */
        if (null != searchVo.getThYears() && searchVo.getThYears() == 1) {

            // 获取当前年份
            int currentYear = Year.now().getValue();

            // 计算三年前的年份
            int yearThreeYearsAgo = currentYear - 3;

            Query rangeQuery = RangeQuery.of(i -> i.field("year").gte(JsonData.fromJson(yearThreeYearsAgo + ".0")).lte(JsonData.fromJson(currentYear + ".0")))._toQuery();
            allQueryBuilder.must(rangeQuery);
        }

        /**
         * 年份过滤 课题思路助手
         */
        if (StringUtil.isNotNull(searchVo.getYear())) {
            List<String> list = covent_(searchVo.getYear());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("year").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 年份过滤 结题基金论文
         */
        if (StringUtil.isNotNull(searchVo.getFundYears())) {
            List<String> list = covent(searchVo.getFundYears());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("year").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 是否是六大刊
         */
        if (null != searchVo.getIsCns()) {
            Query query = TermQuery.of(i -> i.field("is_cns").value(searchVo.getIsCns()))._toQuery();
            allQueryBuilder.must(query);
        }
        /**
         * 期刊过滤
         */
        if (null != searchVo.getJournal()) {
            List<String> list = covent(searchVo.getJournal());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("journal.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        // 2024年10月16日14:01:40 现在有个问题是关于过滤 加入一篇文章里面 有单位 a b  分别对应的 部门 c d 也就是合并切来 有
        // a_c b_d 如果拆开计算 会导致 假如检索结果 出现了 a 单位 那么也会出现 c d 部门 如果点击了过滤会导致没数据 加入点击了一个 a_d
        // 就出现 0  所以在过滤返回左侧时候就需要判断到所有单位对应的部门进行处理

        //单位过滤 unit 葛成瑞新增
        if (StringUtil.isNotNull(searchVo.getUnitNew())) {
            log.info("过滤单位+" + searchVo.getUnitNew());
            List<String> list = covent(searchVo.getUnitNew());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("unit.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        //部门过滤 dept 葛成瑞新增
        if (StringUtil.isNotNull(searchVo.getDept())) {
            log.info("过滤部门+" + searchVo.getDept());
            List<String> list = covent(searchVo.getDept());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("dept.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        // 单位部门过滤 新增
        if (StringUtil.isNotNull(searchVo.getUnitNew()) && StringUtil.isNotNull(searchVo.getDept())) {
            searchVo.setUnitDept(searchVo.getUnitNew() + "_" + searchVo.getDept());
            log.info("过滤单位部门+" + searchVo.getUnitDept());
            List<String> list = covent(searchVo.getUnitDept());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query wildCard = WildcardQuery.of(i -> i.field("unit_dept.wildcard").value(searchVo.getUnitDept()))._toQuery();
            allQueryBuilder.should(wildCard);
        }

        /**
         * 机构过滤
         */
        if (null != searchVo.getUnit()) {
            List<String> list = covent(searchVo.getUnit());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("cn_unit.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 国家过滤
         */
        if (null != searchVo.getCountry()) {
            List<String> list = covent(searchVo.getCountry());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("cn_country.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
            allQueryBuilder.mustNot(TermQuery.of(i -> i.field("cn_country.keyword").value(""))._toQuery());
        }
        /**
         * 作者过滤
         */
        if (null != searchVo.getAuthor()) {
            List<String> list = covent(searchVo.getAuthor());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            allQueryBuilder.must(TermsQuery.of(t -> t.field("auth.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery());
        }

        /**
         * 关键词过滤 2024年11月2日15:06:56 新增
         *
         */
        if (null != searchVo.getKeyWord()) {
            List<String> list = covent(searchVo.getKeyWord());
            BoolQuery.Builder keywordBool = new BoolQuery.Builder();
            for (String s : list) {
                keywordBool.must(TermQuery.of(i -> i.field("keyword.keyword").value(s))._toQuery());
            }
            allQueryBuilder.must(keywordBool.build()._toQuery());
        }

        /**
         * 文献类型
         */
        if (null != searchVo.getPt()) {
            List<String> list = covent(searchVo.getPt());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("pt.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 疾病
         */
        if (CheckUtil.isNotNull(searchVo.getDisease())) {

            List<String> list = covent_(searchVo.getDisease());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("disease.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 基因
         */
        if (CheckUtil.isNotNull(searchVo.getGene())) {

            List<String> list = covent_(searchVo.getGene());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("gene.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 通路
         */
        if (CheckUtil.isNotNull(searchVo.getPathway())) {

            List<String> list = covent_(searchVo.getPathway());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("pathway.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 药物
         */
        if (CheckUtil.isNotNull(searchVo.getDrug())) {

            List<String> list = covent_(searchVo.getDrug());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("drug.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 是否是中国人
         */
        if (searchVo.getIsChina() != null) {
            if (searchVo.getIsChina() == 1) {
                Query idsQuery = TermQuery.of(t -> t.field("is_china").value(1))._toQuery();
                allQueryBuilder.must(idsQuery);
            } else if (searchVo.getIsChina() == 0) {
                Query idsQuery = TermQuery.of(t -> t.field("is_china").value(0))._toQuery();
                allQueryBuilder.must(idsQuery);
            }
        }
        return allQueryBuilder;
    }

    public BoolQuery.Builder getBoolQueryNSFc(ArticleSearchVo searchVo) throws SQLException, IOException {
        BoolQuery.Builder allQueryBuilder = new BoolQuery.Builder();

        //特殊情况一 用户检索词中含有&符号,将其替换成#z#a#f#n#fd#
        String searchWord = searchVo.getPram();
        if (searchWord.startsWith("id=")) {//aid
            searchWord = searchWord.replace("id=", "");
            if (CheckUtil.isNumberRange(searchWord)) {
                String[] split = searchWord.split(",");
                List<FieldValue> values = new ArrayList<>();
                for (String id : split) {
                    values.add(FieldValue.of(id));
                }
                Query idsQuery = TermsQuery.of(t -> t.field("aid").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
                allQueryBuilder.must(idsQuery);
            }

        } else if (searchWord.startsWith("pmid=")) {
            searchWord = searchWord.replace("pmid=", "");
            if (CheckUtil.isNumberRange(searchWord)) {
                String[] split = searchWord.split(",");
                List<FieldValue> values = new ArrayList<>();
                for (String id : split) {
                    values.add(FieldValue.of(id));
                }
                Query idsQuery = TermsQuery.of(t -> t.field("pmid").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
                allQueryBuilder.must(idsQuery);
            }
        } else if (CheckUtil.isNumber(searchWord)) {
            //判断是不是pmid
            searchWord = searchWord.replaceAll("\\[pmid\\]", "");
            searchWord = searchWord.replaceAll("\\[PMID\\]", "");
            String finalPram1 = searchWord;
            TermQuery query = TermQuery.of(i -> i.field("pmid").value(k -> k.stringValue(finalPram1)));
            allQueryBuilder.must(query._toQuery());
            return allQueryBuilder;
        } else {
            /**
             * 核心检索
             */
            BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder();
            if (!StringUtil.isNull(searchWord)) {
                /**
                 * 普通限定词 没有引号 也没有星号
                 *
                 */
                boolean printLog = true;

                Pattern pattern = Pattern.compile(".*\\[([a-zA-Z]+)\\]");
                Matcher matcher = pattern.matcher(searchWord);
                if (matcher.find()) {
                    System.out.println("走限定了");
                    String xian_ding = matcher.group(1);
                    String search_world = searchWord.replace("[" + xian_ding + "]", "").trim();

                    if (xian_ding.equals("encnti")) {
                        xian_ding = "ti";
                    }
                    if (xian_ding.equals("title")) {
                        xian_ding = "ti";
                    }
                    if (xian_ding.equals("abstract")) {
                        xian_ding = "ab";
                    }
                    if (xian_ding.equals("py")) {
                        xian_ding = "year";
                    }
                    if (xian_ding.equals("ta")) {
                        xian_ding = "journal";
                    }
                    if (xian_ding.equals("kw") || xian_ding.equals("keyword")) {
                        xian_ding = "key_word_list";
                    }
                    if (xian_ding.equals("au") || xian_ding.equals("ahthor")) {
                        xian_ding = "auth";
                    }
                    if (xian_ding.equals("mesh")) {
                        search_world = search_world.replaceAll("\\*", "").trim();
                    }
                    zsout("实际使用的检索词___" + search_world, printLog);
                    zsout("实际使用的限定词___" + "[" + xian_ding + "]", printLog);
                    if (xian_ding.equals("TI")) {//如果是DOI
                        String finalPrefix = search_world;
                        BoolQuery.Builder oneQuery = new BoolQuery.Builder();
                        oneQuery.should(MatchQuery.of(i -> i.field("title").query(finalPrefix))._toQuery());
                        boolQueryBuilder.must(oneQuery.build()._toQuery());
                    } else if (xian_ding.equals("AU")) {//如果是作者
                        String finalPrefix1 = search_world;
//                        boolQueryBuilder.must(MatchQuery.of(i -> i.field("auth").query(finalPrefix1.toLowerCase()))._toQuery());
                        //  builder.should(MatchPhraseQuery.of(i -> i.field("journal").query(freeWord.toLowerCase()).slop(0))._toQuery());
                        // 应用对象不同：
                        //MultiMatchQuery.minimumShouldMatch：控制多个字段之间的最小匹配数量（如 95% 表示匹配字段数需达到总字段数的95%）
                        //MatchPhraseQuery：本身没有该参数，它要求单个字段必须完全匹配短语（通过 slop 控制短语的灵活性）
                        //查询逻辑不同：
                        //您的 all_field_match_queryNSFC 方法中，当使用 minimumMatch = "95%" 时，表示在 title/cn_ti/auth/ab 等多个字段中，至少要匹配 95% 的字段
                        //MatchPhraseQuery 的 slop(0) 表示必须严格按照词序完全匹配（如 "machine learning" 不会匹配 "learning machine"）
                        //应用场景不同：
                        //MultiMatch 适用于跨字段的模糊匹配（如同时搜索 title 和 abstract）
                        //MatchPhrase 适用于特定字段的精确短语匹配（如精确匹配标题中的完整短语）
                        //在您的代码中，当 wordCount > 5 时设置 minimumMatch = "95%"，表示当用户输入较长时，要求大部分字段（95%）都需要包含查询词，这是典型的跨字段相关性控制策略。
                        boolQueryBuilder.must(MatchPhraseQuery.of(i -> i.field("auth").query(finalPrefix1).slop(0))._toQuery());
                    } else if (xian_ding.equals("TA")) {//如果是单位的筛选
                        String finalPrefix1 = search_world;
                        boolQueryBuilder.must(TermQuery.of(i -> i.field("journal.keyword").value(finalPrefix1.toLowerCase()))._toQuery());
                    } else if (xian_ding.equals("NSFCUNIT")) {
                        BoolQuery.Builder oneQuery = new BoolQuery.Builder();
                        String finalPrefix1 = search_world;
                        oneQuery.should(MatchQuery.of(i -> i.field("unit.keyword").query(finalPrefix1))._toQuery());
                        boolQueryBuilder.must(oneQuery.build()._toQuery());
                    } else if (xian_ding.equals("TS")) {
                        zsout("[TS][精确][" + search_world + "]",printLog );
                        BoolQuery.Builder builder = new BoolQuery.Builder();
                        String finalSearch_world = search_world;
                        builder.should(MatchPhraseQuery.of(i -> i.field("title").query(finalSearch_world.toLowerCase()).slop(0))._toQuery());
                        builder.should(MatchPhraseQuery.of(i -> i.field("cn_ti").query(finalSearch_world.toLowerCase()).slop(0))._toQuery());
                        builder.should(MatchPhraseQuery.of(i -> i.field("ab").query(finalSearch_world.toLowerCase()).slop(0))._toQuery());
                        builder.should(MatchPhraseQuery.of(i -> i.field("cn_ab").query(finalSearch_world.toLowerCase()).slop(0))._toQuery());
                        builder.should(MatchPhraseQuery.of(i -> i.field("key_word_list").query(finalSearch_world.toLowerCase()).slop(0))._toQuery());
                        boolQueryBuilder.must(builder.build()._toQuery());
                    }
                } else {
                    System.out.println("走自由词");
                    boolQueryBuilder.must(All_Field_Match_query.all_field_match_queryNSFC(searchWord, true));
                }
                allQueryBuilder.must(boolQueryBuilder.build()._toQuery());
            } else {
                log.info("是空检索 不走 走左右过滤测试");
            }
        }

        /**
         * 如果是课题思路助手 和高分选题 只要pm数据
         */
        if (searchVo.getType() != null) {
            if (searchVo.getType().equalsIgnoreCase("QF_Study_Topic_Idea_Assistant") || searchVo.getType().equalsIgnoreCase("HIGH_SCORING_TOPICS")) {
                allQueryBuilder.mustNot(TermQuery.of(i -> i.field("pmid").value(0))._toQuery());
            }
        }

        /**
         * 影响因子过滤
         */
        if (StringUtil.isNotNull(searchVo.getJif())) {
            log.info("影响因子过滤");
            String[] strings = searchVo.getJif().split("###");
            BoolQuery.Builder builder = new BoolQuery.Builder();
            for (String string : strings) {
                String[] split = string.split("_");
                System.out.println("多选影响因子左侧_" + split[0]);
                System.out.println("多选影响因子右侧_" + split[1]);
                System.out.println("--------------");
                Query rangeQuery = RangeQuery.of(i -> i.field("jcr_if").gte(JsonData.fromJson(split[0] + ".0")).lte(JsonData.fromJson(split[1] + ".0")))._toQuery();
                builder.should(rangeQuery);
            }
            allQueryBuilder.must(builder.build()._toQuery());
        }
        /**
         * 年份过滤
         */
        if (CheckUtil.isNotNull(searchVo.getYears())) {
            log.info("年份过滤");
            String pubyear = searchVo.getYears();
            if (pubyear.contains("_")) {
                String[] split = pubyear.split("_");
                Query rangeQuery = RangeQuery.of(i -> i.field("year").gte(JsonData.fromJson(split[0] + ".0")).lte(JsonData.fromJson(split[1] + ".0")))._toQuery();
                allQueryBuilder.must(rangeQuery);
            } else {
                Query toQuery = TermQuery.of(i -> i.field("year").value(pubyear))._toQuery();
                allQueryBuilder.must(toQuery);
            }

        }

        /**
         * 中科院分区
         */
        if (null != searchVo.getZkyDaLei()) {
            log.info("中科院分区");
            List<String> list = covent(searchVo.getZkyDaLei());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("zkydalei").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * JCR分区
         */
        if (null != searchVo.getJcrFenQu()) {
            log.info("JCR分区");
            List<String> list = covent(searchVo.getJcrFenQu());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("jcr_quartile").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        /**
         * 近三年
         */
        if (null != searchVo.getThYears() && searchVo.getThYears() == 1) {

            // 获取当前年份
            int currentYear = Year.now().getValue();

            // 计算三年前的年份
            int yearThreeYearsAgo = currentYear - 3;

            Query rangeQuery = RangeQuery.of(i -> i.field("year").gte(JsonData.fromJson(yearThreeYearsAgo + ".0")).lte(JsonData.fromJson(currentYear + ".0")))._toQuery();
            allQueryBuilder.must(rangeQuery);
        }

        /**
         * 年份过滤 课题思路助手
         */
        if (StringUtil.isNotNull(searchVo.getYear())) {
            List<String> list = covent_(searchVo.getYear());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("year").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 年份过滤 结题基金论文
         */
        if (StringUtil.isNotNull(searchVo.getFundYears())) {
            List<String> list = covent(searchVo.getFundYears());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("year").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 是否是六大刊
         */
        if (null != searchVo.getIsCns()) {
            log.info("是否是六大刊");
            Query query = TermQuery.of(i -> i.field("is_cns").value(searchVo.getIsCns()))._toQuery();
            allQueryBuilder.must(query);
        }
        /**
         * 期刊过滤
         */
        if (null != searchVo.getJournal()) {
            log.info("期刊过滤");
            List<String> list = covent(searchVo.getJournal());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("journal.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        // 2024年10月16日14:01:40 现在有个问题是关于过滤 加入一篇文章里面 有单位 a b  分别对应的 部门 c d 也就是合并切来 有
        // a_c b_d 如果拆开计算 会导致 假如检索结果 出现了 a 单位 那么也会出现 c d 部门 如果点击了过滤会导致没数据 加入点击了一个 a_d
        // 就出现 0  所以在过滤返回左侧时候就需要判断到所有单位对应的部门进行处理

        //单位过滤 unit 葛成瑞新增
        if (StringUtil.isNotNull(searchVo.getUnitNew())) {
            log.info("过滤单位+" + searchVo.getUnitNew());
            List<String> list = covent(searchVo.getUnitNew());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("unit.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        //部门过滤 dept 葛成瑞新增
        if (StringUtil.isNotNull(searchVo.getDept())) {
            log.info("过滤部门+" + searchVo.getDept());
            List<String> list = covent(searchVo.getDept());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("dept.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }

        // 单位部门过滤 新增
        if (StringUtil.isNotNull(searchVo.getUnitNew()) && StringUtil.isNotNull(searchVo.getDept())) {
            searchVo.setUnitDept(searchVo.getUnitNew() + "_" + searchVo.getDept());
            log.info("过滤单位部门+" + searchVo.getUnitDept());
            List<String> list = covent(searchVo.getUnitDept());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query wildCard = WildcardQuery.of(i -> i.field("unit_dept.wildcard").value(searchVo.getUnitDept()))._toQuery();
            allQueryBuilder.should(wildCard);
        }

        /**
         * 机构过滤
         */
        if (null != searchVo.getUnit()) {
            log.info("机构过滤");
            List<String> list = covent(searchVo.getUnit());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("cn_unit.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 国家过滤
         */
        if (null != searchVo.getCountry()) {
            List<String> list = covent(searchVo.getCountry());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("cn_country.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
            allQueryBuilder.mustNot(TermQuery.of(i -> i.field("cn_country.keyword").value(""))._toQuery());
        }
        /**
         * 作者过滤
         */
        if (null != searchVo.getAuthor()) {
            log.info("作者过滤");
            List<String> list = covent(searchVo.getAuthor());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            allQueryBuilder.must(TermsQuery.of(t -> t.field("auth.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery());
        }

        /**
         * 关键词过滤 2024年11月2日15:06:56 新增
         *
         */
        if (null != searchVo.getKeyWord()) {
            log.info("关键词过滤");
            List<String> list = covent(searchVo.getKeyWord());
            BoolQuery.Builder keywordBool = new BoolQuery.Builder();
            for (String s : list) {
                keywordBool.must(TermQuery.of(i -> i.field("keyword.keyword").value(s))._toQuery());
            }
            allQueryBuilder.must(keywordBool.build()._toQuery());
        }

        /**
         * 文献类型
         */
        if (null != searchVo.getPt()) {
            log.info("文献类型");
            List<String> list = covent(searchVo.getPt());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("pt.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 疾病
         */
        if (CheckUtil.isNotNull(searchVo.getDisease())) {
            log.info("疾病");

            List<String> list = covent_(searchVo.getDisease());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("disease.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 基因
         */
        if (CheckUtil.isNotNull(searchVo.getGene())) {

            List<String> list = covent_(searchVo.getGene());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("gene.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 通路
         */
        if (CheckUtil.isNotNull(searchVo.getPathway())) {

            List<String> list = covent_(searchVo.getPathway());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("pathway.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 药物
         */
        if (CheckUtil.isNotNull(searchVo.getDrug())) {

            List<String> list = covent_(searchVo.getDrug());
            List<FieldValue> values = new ArrayList<>();
            for (String id : list) {
                values.add(FieldValue.of(id));
            }
            Query idsQuery = TermsQuery.of(t -> t.field("drug.keyword").terms(new TermsQueryField.Builder().value(values).build()))._toQuery();
            allQueryBuilder.must(idsQuery);
        }
        /**
         * 是否是中国人
         */
        if (searchVo.getIsChina() != null) {
            if (searchVo.getIsChina() == 1) {
                Query idsQuery = TermQuery.of(t -> t.field("is_china").value(1))._toQuery();
                allQueryBuilder.must(idsQuery);
            } else if (searchVo.getIsChina() == 0) {
                Query idsQuery = TermQuery.of(t -> t.field("is_china").value(0))._toQuery();
                allQueryBuilder.must(idsQuery);
            }
        }
        return allQueryBuilder;
    }


    public List<String> covent(String s) {
        if (CheckUtil.isNull(s)) {
            return new ArrayList<>();
        } else {
            return Convert.toList(String.class, s.split("###"));
        }
    }

    public List<String> covent_(String s) {
        if (CheckUtil.isNull(s)) {
            return new ArrayList<>();
        } else {
            return Convert.toList(String.class, s.split("_"));
        }
    }


}
